package org.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.app.entity.ServiceRequest;
import org.app.entity.User;
import org.app.exception.BusinessException;
import org.app.mapper.ServiceRequestMapper;
import org.app.service.ServiceRequestService;
import org.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ServiceRequestServiceImpl extends ServiceImpl<ServiceRequestMapper, ServiceRequest> implements ServiceRequestService {
    
    @Autowired
    private UserService userService;
    
    @Override
    public void reply(Long id, String reply, Long replyUserId) {
        ServiceRequest serviceRequest = getById(id);
        if (serviceRequest == null) {
            throw new BusinessException(404, "服务请求不存在");
        }
        
        serviceRequest.setReply(reply);
        serviceRequest.setReplyTime(LocalDateTime.now());
        serviceRequest.setReplyUserId(replyUserId);
        
        // 如果当前状态是未处理，则更新为处理中
        if (serviceRequest.getStatus() == 0) {
            serviceRequest.setStatus(1);
        }
        
        updateById(serviceRequest);
    }
    
    @Override
    public Page<ServiceRequest> getUserServicePage(Long userId, Integer pageNum, Integer pageSize, Integer type) {
        LambdaQueryWrapper<ServiceRequest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ServiceRequest::getUserId, userId);
        if (type != null) {
            wrapper.eq(ServiceRequest::getType, type);
        }
        wrapper.orderByDesc(ServiceRequest::getCreateTime);
        
        Page<ServiceRequest> page = new Page<>(pageNum, pageSize);
        page = page(page, wrapper);
        
        return page;
    }
    
    @Override
    public Page<ServiceRequest> getAdminServicePage(Integer pageNum, Integer pageSize, Integer type, Integer status) {
        LambdaQueryWrapper<ServiceRequest> wrapper = new LambdaQueryWrapper<>();
        if (type != null) {
            wrapper.eq(ServiceRequest::getType, type);
        }
        if (status != null) {
            wrapper.eq(ServiceRequest::getStatus, status);
        }
        wrapper.orderByDesc(ServiceRequest::getCreateTime);
        
        Page<ServiceRequest> page = new Page<>(pageNum, pageSize);
        page = page(page, wrapper);
        
        // 填充用户信息
        fillUserInfo(page.getRecords());
        
        return page;
    }
    
    @Override
    public ServiceRequest getServiceDetail(Long id) {
        ServiceRequest serviceRequest = getById(id);
        if (serviceRequest == null) {
            throw new BusinessException(404, "服务请求不存在");
        }
        
        // 获取用户信息
        if (serviceRequest.getUserId() != null) {
            User user = userService.getById(serviceRequest.getUserId());
            if (user != null) {
                serviceRequest.setUsername(user.getUsername());
                serviceRequest.setPhone(user.getPhone());
            }
        }
        
        return serviceRequest;
    }
    
    /**
     * 填充用户信息
     */
    private void fillUserInfo(List<ServiceRequest> serviceRequests) {
        // 提取用户ID列表
        List<Long> userIds = serviceRequests.stream()
                .map(ServiceRequest::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        if (!userIds.isEmpty()) {
            // 批量查询用户信息
            List<User> users = userService.listByIds(userIds);
            
            // 构建用户ID到用户信息的映射
            Map<Long, User> userMap = users.stream()
                    .collect(Collectors.toMap(User::getId, user -> user));
            
            // 填充用户信息
            serviceRequests.forEach(serviceRequest -> {
                User user = userMap.get(serviceRequest.getUserId());
                if (user != null) {
                    serviceRequest.setUsername(user.getUsername());
                    serviceRequest.setPhone(user.getPhone());
                }
            });
        }
    }
    
    @Override
    public void revoke(Long id, Long userId) {
        // 查询服务申请
        ServiceRequest serviceRequest = this.getById(id);
        if (serviceRequest == null) {
            throw new BusinessException("服务申请不存在");
        }
        
        // 检查是否是申请人
        if (!serviceRequest.getUserId().equals(userId)) {
            throw new BusinessException("无权撤销他人的服务申请");
        }
        
        // 检查状态是否为处理中
        if (serviceRequest.getStatus() != 1) {
            throw new BusinessException("只有处理中的服务申请可以撤销");
        }
        
        // 更新状态为已撤销
        ServiceRequest update = new ServiceRequest();
        update.setId(id);
        update.setStatus(3); // 3表示已撤销
        this.updateById(update);
    }
    
    @Override
    public void cancel(Long id, Long userId) {
        ServiceRequest request = getById(id);
        if (request == null) {
            throw new BusinessException("服务申请不存在");
        }
        if (!request.getUserId().equals(userId)) {
            throw new BusinessException("无权操作");
        }
        if (request.getStatus() != 0) {
            throw new BusinessException("只有待处理状态的服务申请可以取消");
        }
        request.setStatus(3); // 已取消
        updateById(request);
    }
    
    @Override
    public void confirm(Long id, Long userId) {
        ServiceRequest request = getById(id);
        if (request == null) {
            throw new BusinessException("服务申请不存在");
        }
        if (!request.getUserId().equals(userId)) {
            throw new BusinessException("无权操作");
        }
        if (request.getStatus() != 1) {
            throw new BusinessException("只有处理中状态的服务申请可以确认完成");
        }
        request.setStatus(2); // 已完成
        updateById(request);
    }
} 